<template>
    <div>
        <el-col :span="3">
            <div class="grid-content bg-purple"></div>
            <el-button type="primary" @click="onhandAdd">点餐</el-button>
        </el-col>
        <el-input style="width: 240px;" placeholder="请输入用户名" v-model="params.name"></el-input>
        <el-input style="width: 240px;" placeholder="请输入手机号" v-model="params.tel"></el-input>
        <el-button style="margin-left: 10px;" type="primary" icon="el-icon-search " @click="loads">搜索</el-button>
        <el-button style="margin-left: 10px;" type="warning" icon="el-icon-scissors " @click="reset">重置</el-button>

        <el-table
                :data="tableData"
                stripe
                style="width: 100%">
            <el-table-column
                    type="index"
                    width="50">
            </el-table-column>
            <el-table-column
                    prop="userName"
                    label="用户名"
                    width="110">
            </el-table-column>
            <el-table-column
                    prop="userNum"
                    label="用户编号"
                    width="130">
            </el-table-column>
            <el-table-column
                prop="userTel"
                label="手机号"
                width="150">
            </el-table-column>
            <el-table-column
                    prop="submitTime"
                    label="确认时间"
                    width="230">
                <template v-slot="scope">
                    {{ formattedDate(scope.row.submitTime) }}
                </template>
            </el-table-column>
            <el-table-column
                    prop="finishTime"
                    label="完成时间"
                    width="230">
                <template v-slot="scope">
                    {{ formattedDate(scope.row.finishTime) }}
                </template>
            </el-table-column>
            <el-table-column
                    style="font-size: 16px"
                    prop="orderPrice"
                    label="订单总价格"
                    width="160">
            </el-table-column>
            <el-table-column label="订单状态" prop="status" width="160">
            </el-table-column>
            <el-table-column label="操作" prop="orderId">
                <template v-slot="scope">
                                        <el-popconfirm  confirm-button-text='确认' cancel-button-text='取消' icon="el-icon-info" icon-color="yellow"
                                                       title="确认客人已支付？" @confirm="pay(scope.row.orderId)">
                                            <el-button style="margin-right: 3px" v-if="scope.row.status!= '已完成'" type="primary" slot="reference">订单完成</el-button>
                                        </el-popconfirm>
                    <el-button type="primary" @click="handleEdit(scope.row.orderId)">编辑订单
                    </el-button>

                    <el-popconfirm confirm-button-text='确认' cancel-button-text='取消' icon="el-icon-info"
                                   icon-color="red"
                                   title="确认删除此订单吗？" @confirm="del(scope.row.orderId)">
                        <el-button type="danger" slot="reference">撤单</el-button>
                    </el-popconfirm>
                </template>
            </el-table-column>
        </el-table>
        <!-- 分页 -->
        <div style="margin-top: 10px;">
            <el-pagination background :current-page="params.pageNum" :page-size="params.pageSize"
                           layout="prev, pager, next" :total="total" @current-change="handleCurrentChange">
            </el-pagination>
        </div>

        <!-- 新增编辑弹框 -->
        <el-dialog width="90%" :title="title" :visible.sync="dialogVisible" :before-close="handleClose">
            <div style="display: flex;margin-left: 70px;margin-top: 10px;position: relative;" v-for="(item,index) in caipin">
                <el-avatar  :size="45" :src="item.picture" shape="square"></el-avatar>
                <div style="margin-left: 20px;margin-top: 10px"> {{item.name}}</div>
                <div style="margin-left: 20px;margin-top: 10px"> ￥{{item.count * item.price}}</div>

                <div style="position: absolute;left: 450px;margin-top: 10px">
                    <el-button :disabled="item.count == 0" @click="jiancar(index)" type="primary" icon="el-icon-minus" circle size="mini"></el-button>
                    {{item.count}}
                    <el-button @click="addcar(index)" type="primary" icon="el-icon-plus" circle size="mini"></el-button>
                </div>
            </div>
            <div style="margin-left: 60px;margin-top: 10px;font-size: 20px">
                总价格：￥ {{sum}}
            </div>
            <div style="text-align-last: center;">
                <el-button @click="closedialog()" type="danger" size="medium">取 消</el-button>
                <el-button style="margin-right: 30px;" type="primary" icon="el-icon-upload2 "
                           @click="dialogVisibleConfirm()" size="medium">{{save}}
                </el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import request from "@/request";
import diancai from "@/views/receptionAdmin/diancai.vue";
import Vue from "vue";
export default {
    name: "YuyueOrder",
    components : {diancai},
    data() {
        return {
            dialogVisible: false,
            total: 0,
            tableData: [],
            caipin: [],
            params: {
                pageNum: 1,
                pageSize: 8,

            },
            title:'点餐',
            save: "添加",
            allid: "",
        }
    },
    mounted() {
        this.load()
        this.getAllcaipin()
    },
    computed: {
        sum () {
            let sum = 0
            for (let i = 0; i < this.caipin.length; i++) {
                sum += this.caipin[i].count * this.caipin[i].price
            }
            return  sum
        }
    },
    methods: {
        getAllcaipin(){
            request.get('/caipin/page', {
                params: this.params
            }).then(res => {
                if (res.code === "200") {
                    this.caipin = res.data.list;
                    for (let i = 0; i < this.caipin.length; i++) {
                        Vue.set(this.caipin[i], 'count', 0)
                    }
                }
            })
        },
        onhandAdd() {
            this.title = '点餐';
            this.save = "添加"
            this.resetForm();
            this.dialogVisible = true;
        },
        resetForm() {
            this.$nextTick(() => {
                for (const argument of this.caipin) {
                    argument.count = 0
                }
            })
        },
        //页面加载
        loads() {
            this.params.pageNum = 1
            this.load()
        },
        load() {
            request.get('/order/yuyue', {
                params: this.params
            }).then(res => {
                console.log(res)
                if (res.code === "200") {
                    this.total = res.data.total;
                    this.tableData = res.data.list;

                }
            })
        },
        handleCurrentChange(pageNum) {
            this.params.pageNum = pageNum;
            this.load()
        },
        formattedDate(dateStr) {
            if (!dateStr) {
                return null
            }
            const date = new Date(dateStr);
            const year = date.getFullYear();
            const month = date.getMonth() + 1;
            const day = date.getDate();
            const hours = date.getHours();
            const minutes = date.getMinutes();
            const seconds = date.getSeconds();
            return `${year}年${month}月${day}日${hours}:${minutes}:${seconds}`;
        },
        del(orderId) {
            request.delete('/order/delete' + orderId).then(res => {
                if (res.code === '200') {
                    this.$notify.success('删除成功')
                    this.load();
                } else {
                    this.$notify.error(res.msg)
                }
            })

        },
        //关闭dialog
        handleClose(done) {
            this.load()
            this.dialogVisible = false;
        },
        //编辑按钮，从此处调取修改方法
        handleEdit(chefAdminId) {
            this.save = "保存"
            this.title = '修改订单'
            this.dialogVisible = true; //显示弹框
            this.toOrderInfo(chefAdminId)
            this.allid = chefAdminId; //把id存全局
        },
        toOrderInfo(orderId) {
            let params = {
                orderId: orderId,
                pageNum: 1
            }
            request.get('/order/info', {
                params: params
            }).then(res => {
                if (res.code === "200") {
                    for (const re of res.data.list) {
                        for (const re1 of this.caipin){
                            if (re.caipinId === re1.id){
                                Vue.set(re1,'count',re.count)
                            }
                        }
                    }

                }
            })
            // this.$router.push({path: '/receptionadmin/SYSOrderInfo', query: {param: orderId}});

        },
        pay(orderId) {
            request.put('/order/pay' + orderId).then(res => {
                if (res.code === '200') {
                    this.$notify.success('支付成功')
                    this.load();
                } else {
                    this.$notify.error(res.msg)
                }
            })
        },
        //关闭dialog
        closedialog() {
            this.dialogVisible = false;
            this.resetForm() //清空表格数据
        },
        reset() {
            this.params = {
                name: '',
                tel: '',
                pageNum: 1,
                pageSize: 10
            }
            this.load()
        },
        //核心判断哪一个按钮调用表单组件
        dialogVisibleConfirm() {
            // 新增接口
            if (!this.allid) {
                this.add()

            } else {
                // 修改接口
                this.update();
            }
        },
        update(){
            const params = []
            for (const argument of this.caipin) {
                if (argument.count !== 0){
                    params.push(argument)
                }
            }
            request.post("/diancan/update/"+ this.allid+"/"+this.sum,params).then(res => {
                this.$message.success("订单修改成功！价格为" + this.sum + '元')
                this.dialogVisible=false
                this.load()

            })
        },
        //新增方法
        add() {
            const params = []
            for (const argument of this.caipin) {
                if (argument.count !== 0){
                    params.push(argument)
                }
            }
            let userId = ''
            request.post("/diancan/submit/"+this.sum,params).then(res => {
                this.$message.success("订单提交成功！价格为" + this.sum + '元')
            })
        },
        addcar(index){
            this.caipin[index].count ++
        },
        jiancar(index){
            this.caipin[index].count --
        },

    },


}
</script>

<style scoped>
.el-table {
    /*margin-left: 5vw;*/
}

/*#head  {*/
/*    height: 350px;*/
/*    !*background-image: url("../../assets/aboutbackground.png");*!*/
/*    !*background-size: cover;*!*/
/*    !*background-repeat: no-repeat;*!*/
/*}*/


</style>